package cn.kgc.tangcco.utils.token;

import cn.kgc.tangcco.model.ResponseText;
import cn.kgc.tangcco.model.ResultCode;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.InvalidClaimException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * @author 李昊哲
 * @Description jwt工具类
 * @Description jwt工具类
 * @date 2020/12/10 下午2:20
 */
public abstract class BaseJwtUtil {

    /**
     * 生成token
     *
     * @param key        密钥
     * @param param      playload
     * @param expiryDate token有效期 long类型
     * @return token
     */
    public static String jwtEncode(String key, Map<String, String> param, long expiryDate) {
        // 过期时间
        JWTCreator.Builder builder = JWT.create();
        // payload
        Set<Map.Entry<String, String>> entries = param.entrySet();
        Iterator<Map.Entry<String, String>> iterator = entries.iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            builder.withClaim(entry.getKey(), entry.getValue());
        }
        return builder.withIssuedAt(new Date()).withExpiresAt(new Date(System.currentTimeMillis() + expiryDate)).sign(Algorithm.HMAC256(key));
    }

    /**
     * 解析token
     *
     * @param token token
     * @param key   密钥
     * @return playload
     */
    public static ResponseText<DecodedJWT> jwtDecode(String token, String key) {
        try {
            DecodedJWT verify = JWT.require(Algorithm.HMAC256(key)).build().verify(token);
            return new ResponseText(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMsg(), verify);
        } catch (SignatureVerificationException e) {
            return new ResponseText(ResultCode.INCONSISTENT_SIGNATURE.getCode(), ResultCode.INCONSISTENT_SIGNATURE.getMsg(), null);
        } catch (AlgorithmMismatchException e) {
            return new ResponseText(ResultCode.ALGORITHM_MISMATCH.getCode(), ResultCode.ALGORITHM_MISMATCH.getMsg(), null);
        } catch (TokenExpiredException e) {
            return new ResponseText(ResultCode.TOKEN_EXPIRATION.getCode(), ResultCode.TOKEN_EXPIRATION.getMsg(), null);
        } catch (InvalidClaimException e) {
            return new ResponseText(ResultCode.PALLOAD_INVALID.getCode(), ResultCode.PALLOAD_INVALID.getMsg(), null);
        } catch (Exception e){
            return new ResponseText(ResultCode.EXCEPTION.getCode(), ResultCode.EXCEPTION.getMsg(), null);
        }
    }
}
